package org.example.traffic.organization;

import org.example.traffic.organization.Organization;
import org.example.traffic.videoInfo.Video;
import org.example.traffic.organization.OrganizationRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class OrganizationService {
    private final OrganizationRepository organizationRepository;

    public OrganizationService(OrganizationRepository organizationRepository) {
        this.organizationRepository = organizationRepository;
    }

    public Organization saveOrganization(Organization organization) {
        Organization existingOrganization = organizationRepository.findByName(organization.getName());
        if (existingOrganization!= null && !existingOrganization.getId().equals(organization.getId())) {
            // 如果存在同名组织且不是当前要操作的这个组织（通过ID判断），则抛出异常
            throw new IllegalArgumentException("组织名称已存在");
        }
        return organizationRepository.save(organization);
    }

    public Organization getOrganizationById(Integer id) {
        return organizationRepository.findById(id).orElse(null);
    }


    public List<Organization> getAllOrganizations() {
        return organizationRepository.findAll();
    }


    // 更新组织
    public Organization updateOrganization(Organization organization) throws IllegalArgumentException {
        Organization existingOrganization = organizationRepository.findByName(organization.getName());
        if (existingOrganization!= null && !existingOrganization.getId().equals(organization.getId())) {
            // 如果存在同名组织且不是当前要更新的这个组织（通过ID判断），抛出异常
            throw new IllegalArgumentException("组织名称已存在");
        }
        return organizationRepository.save(organization);
    }
    // 分页查询视频
    public Page<Organization> getOrganizations(int page, int size) {
        Pageable pageable = PageRequest.of(page, size);
        return organizationRepository.findAll(pageable);
    }
    // 根据名称模糊查询
    public Page<Organization> getOrganizationsByName(String name, int page, int size) {
        return organizationRepository.findByNameContainingIgnoreCase(name, PageRequest.of(page, size));
    }
    public void deleteOrganizationById(Integer id) {
        organizationRepository.deleteById(id);
    }

}
